﻿using System.Collections.Generic;
using System.Linq;
using LanShellManager.Controllers;

namespace LanShellManager.Models
{
    public class ShellCommandRepository:IShellCommandRepository
    {
        private ShellCommandsEntities entities;

        public ShellCommandRepository()
        {
            entities = new ShellCommandsEntities();
        }

        public List<ShellCommandVm> GetCommands()
        {
            List<ShellCommand> commands = entities.ShellCommands.ToList();
            List<ShellCommandVm> result = new List<ShellCommandVm>();
            foreach (var command in commands)
            {
                result.Add(new ShellCommandVm() { Id = command.Id, Text = command.Text});
            }
            return result;
        }

        public ShellCommandVm Find(int id)
        {
            ShellCommand command=entities.ShellCommands.FirstOrDefault(m=> m.Id==id);
            ShellCommandVm result = new ShellCommandVm();
            result.Id = command.Id;
            result.Text = command.Text;
            return result;
        }

        public void Delete(int id)
        {
            ShellCommand command=entities.ShellCommands.FirstOrDefault(m=> m.Id==id);
            entities.ShellCommands.Remove(command);
            entities.SaveChanges();
        }

        public void Update(ShellCommandVm commandVm)
        {
            ShellCommand command = entities.ShellCommands.FirstOrDefault(m => m.Id == commandVm.Id);
            if (command != null) command.Text=commandVm.Text;
            entities.SaveChanges();
        }

        public void Add(ShellCommandVm command)
        {
            entities.ShellCommands.Add(new ShellCommand(){Id = command.Id, Text = command.Text});
            entities.SaveChanges();
        }
    }
}
